<?php

namespace app\client\controller;

use app\common\controller\Frontend;
use app\common\model\banxi\student\Student;
use app\common\service\SmsService;
use app\common\service\WeAppletService;
use think\exception\ValidateException;
use think\facade\Validate;
use think\validate\ValidateRule;

class Login extends Frontend
{
    protected array $noNeedLogin = ['pwdLogin', 'wechatLogin', 'registerLogin', 'checkLogin', 'smsLogin', 'phoneExist', 'loginForgotPassword'];

    protected array $noNeedPermission = ['*'];

    public function initialize(): void
    {
        parent::initialize();
    }


    /**
     * 密码登录
     * @return void
     */
    public function pwdLogin(): void
    {
        $param = $this->request->param([
            'account' => '',
            'password' => '',
            'weMiniCode' => ''
        ]);
        try {
            $validate = Validate::rule([
                'account' => ValidateRule::isRequire(null, '请输入账号'),
                'password' => ValidateRule::isRequire(null, '请输入密码')
            ]);
            if (!$validate->check($param)) throw new ValidateException($validate->getError());
        } catch (ValidateException $exception) {
            $this->fail($exception->getMessage());
        }
        //获取openid
        $openid = '';
        if ($param['weMiniCode']) {
            $weAppletService = new WeAppletService();
            $openid = $weAppletService->getAppletInfo($param['weMiniCode']);
            if (!$openid) {
                $this->fail($weAppletService->getError());
            }
        }
        //登录
        $res = $this->auth->loginPwd($param['account'], $param['password'], $openid);
        if (!$res) {
            $this->fail($this->auth->getError());
        }
        $this->ok('登录成功', $res);
    }


    /**
     * 微信登录
     * @return void
     */
    public function wechatLogin(): void
    {
        $param = $this->request->param([
            'code' => '',
        ]);
        try {
            $validate = Validate::rule([
                'code' => ValidateRule::isRequire(null, '请输入code'),
            ]);
            if (!$validate->check($param)) throw new ValidateException($validate->getError());
        } catch (ValidateException $exception) {
            $this->fail($exception->getMessage());
        }
        $weAppletService = new WeAppletService();
        $openid = $weAppletService->getAppletInfo($param['code']);
        if (!$openid) {
            $this->fail($weAppletService->getError());
        }
        //登录
        $res = $this->auth->weMiniLogin($openid);
        if (!$res) {
            $this->fail($this->auth->getError(), [
                'isLogin' => $this->auth->isLogin(),
                'openid' => $openid
            ]);
        }
        $this->ok('登录成功', $res);
    }

    /**
     * 验证吗登录
     * @return void
     */
    public function smsLogin(): void
    {
        $param = $this->request->param([
            'phone' => '',
            'code' => ''
        ]);
        try {
            $validate = Validate::rule([
                'phone' => ValidateRule::isRequire(null, '请输入手机号')->isMobile(null, '请输入正确的手机号'),
                'code' => ValidateRule::isRequire(null, '请输入验证码'),
            ]);
            if (!$validate->check($param)) throw new ValidateException($validate->getError());
        } catch (ValidateException $exception) {
            $this->fail($exception->getMessage());
        }
        $res = $this->auth->smsLogin($param['phone'], $param['code']);
        if (!$res) {
            $this->fail($this->auth->getError());
        }
        $this->ok('登录成功', $res);
    }

    /**
     * 修改密码(未使用)
     * @return void
     */
    public function forgotPassword(): void
    {
        $param = $this->request->param([
            'shortMessageCode' => '',
            'password' => '',
        ]);
        try {
            $validate = Validate::rule([
                'shortMessageCode' => ValidateRule::isRequire(null, '请输入短信验证'),
                'password' => ValidateRule::isRequire(null, '请输入新密码')
            ]);
            if (!$validate->check($param)) throw new ValidateException($validate->getError());
        } catch (ValidateException $exception) {
            $this->fail($exception->getMessage());
        }
        $smsService = new SmsService();
        $userInfo = $this->auth->getUserInfo();
        //验证短信验证码
        $res = $smsService->verifySms($userInfo['phone'], $param['shortMessageCode'], 'userForgotPassword');
        if (!$res) {
            $this->fail($smsService->getError());
        }
        //修改密码
        $res = $this->auth->forgotPassword($param['password']);
        if (!$res) {
            $this->fail($this->auth->getError());
        }
        $this->ok();
    }

    /**
     * 忘记密码
     * @return void
     */
    public function loginForgotPassword(): void
    {
        $param = $this->request->param([
            'phone' => '',
            'shortMessageCode' => '',
            'password' => '',
        ]);
        try {
            $validate = Validate::rule([
                'phone' => ValidateRule::isRequire(null, '请输入手机号')->isMobile(null, '请输入正确的手机号'),
                'shortMessageCode' => ValidateRule::isRequire(null, '请输入短信验证'),
                'password' => ValidateRule::isRequire(null, '请输入新密码')
            ]);
            if (!$validate->check($param)) throw new ValidateException($validate->getError());
        } catch (ValidateException $exception) {
            $this->fail($exception->getMessage());
        }
        $userInfo = Student::where('phone', $param['phone'])->find();
        if (!$userInfo) {
            $this->fail('手机号未注册');
        }
        $this->auth->setUser($userInfo);
        //验证短信验证码
        $smsService = new SmsService();
        $res = $smsService->verifySms($param['phone'], $param['shortMessageCode'], 'userForgotPassword');
        if (!$res) {
            $this->fail($this->auth->getError());
        }

        //修改密码
        $res = $this->auth->forgotPassword($param['password']);
        if (!$res) {
            $this->fail($this->auth->getError());
        }
        $this->ok();
    }

    /**
     * 登录验证
     * @return void
     */
    public function checkLogin(): void
    {
        $is_login = $this->auth->isLogin();
        $this->ok(__('Operation completed'), $is_login);
    }

    /**
     * 查询-手机号是否存在
     * @return void
     */
    public function phoneExist(): void
    {
        $param = $this->request->param([
            'phone' => ''
        ]);

        try {
            $validate = Validate::rule([
                'phone' => ValidateRule::isRequire(null, '请输入手机号')->isMobile(null, '请输入正确的手机号'),
            ]);
            if (!$validate->check($param)) throw new ValidateException($validate->getError());
        } catch (ValidateException $exception) {
            $this->fail($exception->getMessage());
        }

        $res = Student::getByPhone($param['phone']) !== null;
        $this->ok(__('Operation completed'), $res);
    }

    /**
     * 重置密码
     * @return void
     */
    public function reUpdatePwd(): void
    {
        $param = $this->request->param([
            'phone' => '',
            'shortMessageCode' => '',
            'password' => '',
        ]);
        try {
            $validate = Validate::rule([
                'phone' => ValidateRule::isRequire(null, '请输入手机号')->isMobile(null, '请输入正确的手机号'),
                'shortMessageCode' => ValidateRule::isRequire(null, '请输入短信验证'),
                'password' => ValidateRule::isRequire(null, '请输入新密码')
            ]);
            if (!$validate->check($param)) throw new ValidateException($validate->getError());
        } catch (ValidateException $exception) {
            $this->fail($exception->getMessage());
        }
        $smsService = new SmsService();
        $userInfo = $this->auth->getUserInfo();
        if ($userInfo['phone'] != $param['phone']) {
            $this->fail('手机号与当前账户不一致');
        }
        //验证短信验证码
        $res = $smsService->verifySms($userInfo['phone'], $param['shortMessageCode'], 'userUpdatePassword');
        if (!$res) {
            $this->fail($this->auth->getError());
        }
        //修改密码
        $res = $this->auth->forgotPassword($param['password']);
        if (!$res) {
            $this->fail($this->auth->getError());
        }
        $this->ok();
    }


    /**
     * 登出
     * @return void
     */
    public function logout()
    {
        $this->auth->logout();
        $this->ok(__('Token expiration'));
    }
}